<?php
set_time_limit(0);
/**
 * 此文件用于信息包内容排序数字清理
 */

$link = mysql_connect('127.0.0.1', 'root', '');
mysql_select_db('nn_cms');
mysql_set_charset('utf8');

echo '<pre>';
$topic_id_arr = get_topic_id_list($link);

foreach ($topic_id_arr as $topic_id){ // 单个信息包
	$category_id_arr = get_topic_category_by_topic_id($link, $topic_id);
	foreach ($category_id_arr as $category_id){ // 单个信息 单个栏目
		$date_arr = get_datediff_by_category_id_and_topic_id($link, $topic_id, $category_id);
		foreach ($date_arr as $date){ // 单个信息 单个栏目 单个时间段
			set_order_by_topic_id_and_category_id_and_date($link, $topic_id, $category_id, $date);
		}
	}
}

function get_topic_id_list($db){
	$sql = 'select DISTINCT nns_topic_id FROM nns_topic_item';
	$result = mysql_query($sql, $db);
	$return = array();
	while ($row = mysql_fetch_object($result)){
		$return[] = $row->nns_topic_id;
	}
	
	return $return;
}

function get_topic_category_by_topic_id($db, $topic_id){
	$sql = 'select DISTINCT nns_category_id from nns_topic_item where nns_topic_id=\''.$topic_id.'\'';
	$result = mysql_query($sql, $db);
	$return = array();
	while ($row = mysql_fetch_object($result)){
		$return[] = $row->nns_category_id;
	}
	return $return;
}

function get_datediff_by_category_id_and_topic_id($db, $topic_id, $category_id){
	$sql = 'select nns_create_time from nns_topic_item where nns_topic_id=\''.$topic_id.'\' 
			and nns_category_id=\''.$category_id.'\'';
	$result = mysql_query($sql, $db);
	$return = array();
	while ($row = mysql_fetch_object($result)){
		$key = date('Y-m-d', strtotime($row->nns_create_time));
		$return[$key] = count($return);
	}
	if(count($result)){
		return array_keys($return);
	}
	return $return;
}

function set_order_by_topic_id_and_category_id_and_date($db, $topic_id, $category_id, $date){
	$date_s = $date.' 00:00:00';
	$date_e = $date.' 23:59:59';
	
	$sql = 'select nns_id from nns_topic_item where nns_topic_id=\''.$topic_id.'\' 
			and nns_category_id=\''.$category_id.'\' and 
			nns_create_time between \''.$date_s.'\' and \''.$date_e.'\' order by nns_order ASC';
	$result = mysql_query($sql, $db);
	$order = 0;
	echo $topic_id.'-'.$category_id.'-'.$date.'<br>';
	while ($row = mysql_fetch_object($result)){
		$sql = 'update nns_topic_item set nns_order='.$order.' where nns_id=\''.$row->nns_id.'\'';
		mysql_query($sql, $db);
		echo $row->nns_id.' '.$order.'<br>';
		$order++;
	}
	echo '<hr>';
}


